<?php
require_once 'ctlAbstract.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busMessage.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busAvatar.php';

class MessageController extends AbstractController {
	private $_messageBus;
	private $_avatarBus;
	
	public function main(array $getVars) {
		global $ubi;
		
		$this->_messageBus = new MessageBus();
		$this->_avatarBus = new AvatarBus(); 
		
		$userID = $_SESSION['userid'];
		if ($getVars['type'] == 'allMessages') {
			if ($userID != null) {
				$arrMess = $this->_messageBus->getAllMessagesByReceiverId($userID);
				$arrUser = $this->_messageBus->getSenderOfMessages($arrMess);
				$imgs = $this->_avatarBus->getAvatarPathOfUsers($arrUser);								
				
				$page = 0;
				if (isset($getVars['page'])) {
					$page = $getVars['page'];
				}
				$nPage = (int)(count($arrMess) / $ubi['SITE']['NUMBER_MESSAGE']) + 1;
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewMessage.php';
			}
		} else if ($getVars['type'] == 'allReadMessages') {
			if ($userID != null) {
				if (!isset($getVars['page'])) {
					$getVars['page'] = 1;
				}				

				$nTotalReadMessage = $this->_messageBus->countReadMessages($userID);
				$numberOfPages = (int)(($nTotalReadMessage - 1) / $ubi['MESSAGE']['MESSAGE_PER_PAGE']  + 1);
				if ($getVars['page'] == 'last') {
					$getVars['page'] = $numberOfPages;
				}								
								
				$arrMess = $this->_messageBus->getReadMessagesByReceiverId($userID, $getVars['page']);
				$arrUser = $this->_messageBus->getSenderOfMessages($arrMess);
				$imgs = $this->_avatarBus->getAvatarPathOfUsers($arrUser);
				
				require_once $ubi['SERVER']['SERVER_ROOT'] . '/view/viewReadMessage.php';
			}
		} else if ($getVars['type'] == 'read') {
			if ($userID != null && isset($_POST['id'])) {
				echo $this->_messageBus->readMessage($_POST['id']);
			}
		}  else if ($getVars['type'] == 'delete') {
			if ($userID != null && isset($_POST['id'])) {
				echo $this->_messageBus->deleteMessage($_POST['id']);
			}
		}
	}
}
?>